package com.example.sp20240522;

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public static int totalFruit1(int[] f) {
        Map<Integer, Integer> hash = new HashMap<>();

        int ret = -1;
        for (int left = 0, right = 0; right < f.length; right++){
            int in = f[right];
            hash.put(in, hash.getOrDefault(in, 0) + 1);

            while (hash.size() > 2){
                int out = f[left];
                hash.put(out, hash.get(out) - 1);

                if (hash.get(out) == 0){
                    hash.remove(out);
                }else{
                    left++;
                }
            }

            ret = Math.max(ret, right - left + 1);
        }

        return ret;
    }


    public static int totalFruit(int[] f)
    {
        Map<Integer, Integer> hash = new HashMap<>();

        int ret = 0;
        for(int left = 0, right = 0; right < f.length; right++)
        {
            int in = f[right];
            hash.put(in, hash.getOrDefault(in, 0) + 1);

            while(hash.size() > 2)
            {
                int out = f[left];
                hash.put(out, hash.get(out) - 1);

                if(hash.get(out) == 0)
                    hash.remove(out);
                left++;
            }

            ret = Math.max(ret, right - left + 1);
        }
        return ret;
    }
    public static void main(String[] args) {
//        int ret = totalFruit1(new int[]{0, 1, 2, 2});
//        System.out.println(ret);

        int ret = totalFruit(new int[]{0, 1, 2, 2});
        System.out.println(ret);

    }
}
